package GlobalWindow_CountWindow;

import bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.evictors.TimeEvictor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.CountTrigger;
import org.apache.flink.util.Collector;

/**
 * @author Spring_Hu
 * @date 2021/10/13 20:07
 */
public class GlobalWindow {
    //globalWindow其实是countWindow的自定义 自定义需要用到触发器和清除器
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("hadoop102",8888)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0],Long.parseLong(split[1]),Integer.parseInt(split[2]));
                    }
                })
                .keyBy(value -> value.getId())
                .window(GlobalWindows.create())
                .trigger(CountTrigger.of(5))
                .evictor(TimeEvictor.of(Time.seconds(3)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, org.apache.flink.streaming.api.windowing.windows.GlobalWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        System.out.println(elements.spliterator().estimateSize());
                        for (WaterSensor element : elements) {
                            out.collect("采集的值："+element);
                        }

                    }
                }).print();

        env.execute();

    }
}
